// index.js
const chalk = require('chalk');
const path = require('path');
const fs = require('fs');
const commonUtil = require('./util/common');

const resolve = (...file) => path.resolve(__dirname, ...file);
const log = (message) => console.log(chalk.green(`${message}`));
const successLog = (message) => console.log(chalk.blue(`${message}`));
const errorLog = (error) => console.log(chalk.red(`${error}`));
// 导入模板
const { vueTemplate, modalTemplate, dataTemplate, apiTemplate, modelTemplate, routeTemplate } = require('./template');
// 生成文件
const generateFile = (path, data) => {
  if (fs.existsSync(path)) {
    errorLog(`${path}文件已存在`);
    return;
  }
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, 'utf8', (err) => {
      if (err) {
        errorLog(err.message);
        reject(err);
      } else {
        resolve(true);
      }
    });
  });
};
log('请输入要生成的页面组件名称、会生成在 views/目录下');
let componentName = '';
process.stdin.on('data', async (chunk) => {
  // 组件名称
  const inputName = String(chunk).trim().toString();

  // 驼峰组件名
  const H_T_C_N = commonUtil.upperFirst(inputName);

  // Vue页面组件路径
  const componentPath = resolve('../src/views', inputName);
  // 请求地址
  const servicePath = resolve('../src/api', inputName);
  const modelPath = resolve(servicePath, 'model');
  // route文件路径
  const routePath = resolve('../src/router/routes/modules')

  // vue文件
  const vueFile = resolve(componentPath, 'index.vue');
  const editFile = resolve(componentPath, H_T_C_N + 'Drawer.vue');
  const dataFile = resolve(componentPath, inputName + '.data.ts');

  // api文件
  const apiFile = resolve(servicePath, 'index.ts');
  const modelFile = resolve(modelPath, 'index.ts');

  // route文件
  const routeFile = resolve(routePath, inputName + '.ts')

  const cDireArray = [
    componentPath,
    servicePath,
    modelPath
  ]

  for (let i = 0; i < cDireArray.length; i++) {
    const element = cDireArray[i];

    // 判断组件文件夹是否存在
    const hasComponentExists = fs.existsSync(element);
    if (hasComponentExists) {
      errorLog(`${element}已存在，请重新输入`);
    } else {
      log(`正在生成 ${element}`);
      await dotExistDirectoryCreate(element);
    }
  }

  try {
    // 获取组件名
    if (inputName.includes('/')) {
      const inputArr = inputName.split('/');
      componentName = inputArr[inputArr.length - 1];
    } else {
      componentName = inputName;
    }
    log(`正在生成 IndexVue 文件 ${vueFile}`);
    await generateFile(vueFile, vueTemplate(componentName));
    log(`正在生成 EditVue 文件 ${editFile}`);
    await generateFile(editFile, modalTemplate(componentName));
    log(`正在生成 data 文件 ${dataFile}`);
    await generateFile(dataFile, dataTemplate(componentName));
    log(`正在生成 api 文件 ${apiFile}`);
    await generateFile(apiFile, apiTemplate(componentName));
    log(`正在生成 model 文件 ${modelFile}`);
    await generateFile(modelFile, modelTemplate(componentName));
    log(`正在生成 route 文件 ${routeFile}`);
    await generateFile(routeFile, routeTemplate(componentName));
    successLog('生成成功');
  } catch (e) {
    errorLog(e.message);
  }

  process.stdin.emit('end');
});
process.stdin.on('end', () => {
  log('exit');
  process.exit();
});

function dotExistDirectoryCreate(directory) {
  return new Promise((resolve) => {
    mkdirs(directory, function () {
      resolve(true);
    });
  });
}
// 递归创建目录
function mkdirs(directory, callback) {
  var exists = fs.existsSync(directory);
  if (exists) {
    callback();
  } else {
    mkdirs(path.dirname(directory), function () {
      fs.mkdirSync(directory);
      callback();
    });
  }
}
